from typing import Dict, Any, List
import httpx
import hmac
import hashlib
from intelli_port.commons.config import load_settings
from intelli_port.data_layer.clients import mysql_execute_read


def _sign(secret: str, body: bytes) -> str:
    return hmac.new(secret.encode("utf-8"), body, hashlib.sha1).hexdigest()


def get_webhooks(flight_no: str) -> List[Dict[str, Any]]:
    try:
        rows = mysql_execute_read("SELECT `value` FROM kv_config WHERE `key`=%s", (f"webhook.flight.{flight_no}",), fetch="one").get("rows", [])
        if rows and rows[0] and rows[0][0]:
            import json
            return json.loads(rows[0][0])
    except Exception:
        return []
    return []


def add_webhook(flight_no: str, url: str, secret: str | None = None) -> bool:
    try:
        lst = get_webhooks(flight_no)
        lst.append({"url": url, "secret": secret or ""})
        import json
        mysql_execute_read("SELECT 1", fetch="one")
        from intelli_port.data_layer.clients import mysql_execute_write
        mysql_execute_write("REPLACE INTO kv_config(`key`,`value`,updated_at) VALUES(%s,%s,NOW())", (f"webhook.flight.{flight_no}", json.dumps(lst)))
        return True
    except Exception:
        return False


def send_webhooks(flight_no: str, payload: Dict[str, Any]) -> int:
    s = load_settings()
    count = 0
    items = get_webhooks(flight_no)
    for it in items:
        try:
            url = str(it.get("url") or "")
            sec = str(it.get("secret") or "")
            body = payload.copy()
            import json
            data = json.dumps(body).encode("utf-8")
            headers = {}
            if sec:
                headers["X-Signature"] = _sign(sec, data)
            with httpx.Client(timeout=float(getattr(s, "webhook_timeout_s", 2.0))) as client:
                client.post(url, content=data, headers=headers)
            count += 1
        except Exception:
            pass
    return count


def get_robot_webhooks(robot_id: int) -> List[Dict[str, Any]]:
    try:
        rows = mysql_execute_read("SELECT `value` FROM kv_config WHERE `key`=%s", (f"webhook.robot.{robot_id}",), fetch="one").get("rows", [])
        if rows and rows[0] and rows[0][0]:
            import json
            return json.loads(rows[0][0])
    except Exception:
        return []
    return []


def add_robot_webhook(robot_id: int, url: str, secret: str | None = None) -> bool:
    try:
        lst = get_robot_webhooks(robot_id)
        lst.append({"url": url, "secret": secret or ""})
        import json
        mysql_execute_read("SELECT 1", fetch="one")
        from intelli_port.data_layer.clients import mysql_execute_write
        mysql_execute_write("REPLACE INTO kv_config(`key`,`value`,updated_at) VALUES(%s,%s,NOW())", (f"webhook.robot.{robot_id}", json.dumps(lst)))
        return True
    except Exception:
        return False


def send_robot_webhooks(robot_id: int, payload: Dict[str, Any]) -> int:
    s = load_settings()
    count = 0
    items = get_robot_webhooks(robot_id)
    for it in items:
        try:
            url = str(it.get("url") or "")
            sec = str(it.get("secret") or "")
            body = payload.copy()
            import json
            data = json.dumps(body).encode("utf-8")
            headers = {}
            if sec:
                headers["X-Signature"] = _sign(sec, data)
            with httpx.Client(timeout=float(getattr(s, "webhook_timeout_s", 2.0))) as client:
                client.post(url, content=data, headers=headers)
            count += 1
        except Exception:
            pass
    return count